import React, { useState, useEffect } from 'react';
import { useNavigate, Link } from 'react-router-dom';
import axios from 'axios';
import { FaCopy, FaTrashAlt, FaEye, FaCalendarPlus, FaExclamationTriangle } from 'react-icons/fa';
import { toast } from 'react-toastify';
import NavBar from '../components/NavBar';
import Modal from '../components/Modal';
import './styles.css';

function Shared() {
  const [shares, setShares] = useState([]);
  const [loading, setLoading] = useState(true);
  const [showDeleteModal, setShowDeleteModal] = useState(false);
  const [showExtendModal, setShowExtendModal] = useState(false);
  const [selectedShare, setSelectedShare] = useState(null);
  const [extendDays, setExtendDays] = useState(7);
  const navigate = useNavigate();

  // 获取所有共享链接
  useEffect(() => {
    fetchShares();
  }, []);

  const fetchShares = async () => {
    setLoading(true);
    try {
      const response = await axios.get('/api/docs/shares');
      // 确保document_id在前端处理时是数字类型
      const processedShares = response.data.map(share => ({
        ...share,
        document_id: Number(share.document_id) // 确保document_id是数字
      }));
      setShares(processedShares);
    } catch (error) {
      console.error('获取共享链接失败:', error);
      toast.error('获取共享链接失败');
    } finally {
      setLoading(false);
    }
  };

  // 复制共享链接
  const copyShareLink = async (link) => {
    try {
      // 优先使用现代Clipboard API
      if (navigator.clipboard && navigator.clipboard.writeText) {
        await navigator.clipboard.writeText(link);
        toast.success('链接已复制到剪贴板');
      } else {
        // 回退到传统方法
        const textArea = document.createElement('textarea');
        textArea.value = link;
        
        // 设置样式使元素不可见但可访问
        textArea.style.position = 'fixed';
        textArea.style.top = '0';
        textArea.style.left = '0';
        textArea.style.width = '2em';
        textArea.style.height = '2em';
        textArea.style.padding = '0';
        textArea.style.border = 'none';
        textArea.style.outline = 'none';
        textArea.style.boxShadow = 'none';
        textArea.style.background = 'transparent';
        
        document.body.appendChild(textArea);
        textArea.focus();
        textArea.select();
        
        // 尝试执行复制命令
        const successful = document.execCommand('copy');
        document.body.removeChild(textArea);
        
        if (successful) {
          toast.success('链接已复制到剪贴板');
        } else {
          toast.warning('请手动选择链接并复制');
        }
      }
    } catch (error) {
      console.error('复制失败:', error);
      toast.warning('自动复制失败，请手动选择并复制链接');
      
      // 尝试将链接选中或者至少显示给用户
      const inputElement = document.querySelector(`input[value="${link}"]`);
      if (inputElement) {
        inputElement.focus();
        inputElement.select();
      }
    }
  };

  // 打开删除确认框
  const confirmDelete = (share) => {
    setSelectedShare(share);
    setShowDeleteModal(true);
  };

  // 删除共享链接
  const handleDelete = async () => {
    if (!selectedShare) return;

    try {
      await axios.delete(`/api/docs/shares/${selectedShare.id}`);
      setShares(shares.filter(share => share.id !== selectedShare.id));
      setShowDeleteModal(false);
      toast.success('共享链接已删除');
    } catch (error) {
      console.error('删除共享链接失败:', error);
      toast.error('删除共享链接失败');
    }
  };

  // 打开延长有效期确认框
  const openExtendModal = (share) => {
    setSelectedShare(share);
    setShowExtendModal(true);
  };

  // 延长共享链接有效期
  const handleExtend = async () => {
    if (!selectedShare) return;

    try {
      const response = await axios.put(`/api/docs/shares/${selectedShare.id}/extend`, {
        days: extendDays
      });
      
      // 更新列表中对应的共享链接
      setShares(shares.map(share => 
        share.id === selectedShare.id 
          ? { ...share, expires_at: response.data.expiresAt } 
          : share
      ));
      
      setShowExtendModal(false);
      toast.success(`共享链接有效期已延长${extendDays}天`);
    } catch (error) {
      console.error('延长共享链接有效期失败:', error);
      toast.error('延长共享链接有效期失败');
    }
  };

  // 检查链接是否已过期
  const isExpired = (expiresAt) => {
    return new Date(expiresAt) < new Date();
  };

  // 格式化日期显示
  const formatDate = (dateStr) => {
    const date = new Date(dateStr);
    return date.toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit'
    });
  };

  // 计算剩余时间
  const getRemainingTime = (expiresAt) => {
    const now = new Date();
    const expiry = new Date(expiresAt);
    const diffMs = expiry - now;
    
    if (diffMs <= 0) {
      return '已过期';
    }
    
    const diffDays = Math.floor(diffMs / (1000 * 60 * 60 * 24));
    const diffHours = Math.floor((diffMs % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
    
    if (diffDays > 0) {
      return `${diffDays}天${diffHours}小时`;
    } else {
      return `${diffHours}小时`;
    }
  };

  // 查看文档
  const viewDocument = (share) => {
    console.log('查看文档:', share);
    // 确保document_id是数字，并使用完整的shareLink进行导航
    if (share && share.shareLink) {
      window.open(share.shareLink, '_blank');
    } else {
      toast.error('共享链接无效');
    }
  };

  return (
    <div className="shared-container">
      <NavBar />
      
      <div className="shared-header">
        <h1>共享链接管理</h1>
      </div>
      
      {loading ? (
        <div className="loading">加载中...</div>
      ) : (
        <>
          {shares.length === 0 ? (
            <div className="no-shares">
              <p>您还没有创建任何共享链接</p>
              <Link to="/docs" className="btn btn-primary">
                返回我的文档
              </Link>
            </div>
          ) : (
            <div className="shares-list">
              <div className="share-list-header">
                <div className="share-col">文档标题</div>
                <div className="share-col">共享链接</div>
                <div className="share-col">创建时间</div>
                <div className="share-col">过期时间</div>
                <div className="share-col">剩余时间</div>
                <div className="share-col">操作</div>
              </div>
              
              {shares.map(share => (
                <div 
                  key={share.id} 
                  className={`share-item ${isExpired(share.expires_at) ? 'expired' : ''}`}
                >
                  <div className="share-col">
                    <div className="document-title">
                      {share.document_title}
                    </div>
                  </div>
                  
                  <div className="share-col">
                    <div className="share-link">
                      <input 
                        type="text" 
                        value={share.shareLink} 
                        readOnly 
                        className="share-link-input" 
                      />
                      <button 
                        onClick={() => copyShareLink(share.shareLink)} 
                        className="action-btn"
                        title="复制链接"
                      >
                        <FaCopy />
                      </button>
                    </div>
                  </div>
                  
                  <div className="share-col">
                    {formatDate(share.created_at)}
                  </div>
                  
                  <div className="share-col">
                    {formatDate(share.expires_at)}
                    {isExpired(share.expires_at) && (
                      <span className="expired-tag">
                        <FaExclamationTriangle /> 已过期
                      </span>
                    )}
                  </div>
                  
                  <div className="share-col">
                    <span className={isExpired(share.expires_at) ? 'expired-time' : 'remaining-time'}>
                      {getRemainingTime(share.expires_at)}
                    </span>
                  </div>
                  
                  <div className="share-col share-actions">
                    <button 
                      onClick={() => viewDocument(share)} 
                      className="action-btn view-btn"
                      title="查看文档"
                    >
                      <FaEye />
                    </button>
                    <button 
                      onClick={() => openExtendModal(share)} 
                      className="action-btn extend-btn"
                      title="延长有效期"
                    >
                      <FaCalendarPlus />
                    </button>
                    <button 
                      onClick={() => confirmDelete(share)} 
                      className="action-btn delete-btn"
                      title="删除共享"
                    >
                      <FaTrashAlt />
                    </button>
                  </div>
                </div>
              ))}
            </div>
          )}
        </>
      )}
      
      {/* 删除确认模态框 */}
      <Modal
        isOpen={showDeleteModal}
        onClose={() => setShowDeleteModal(false)}
        title="确认删除"
      >
        <div className="delete-confirmation">
          <p>确定要删除 "{selectedShare?.document_title}" 的共享链接吗？</p>
          <p className="warning">删除后，任何人都无法通过此链接访问文档！</p>
          <div className="modal-actions">
            <button 
              className="btn btn-secondary" 
              onClick={() => setShowDeleteModal(false)}
            >
              取消
            </button>
            <button 
              className="btn btn-danger" 
              onClick={handleDelete}
            >
              删除
            </button>
          </div>
        </div>
      </Modal>
      
      {/* 延长有效期模态框 */}
      <Modal
        isOpen={showExtendModal}
        onClose={() => setShowExtendModal(false)}
        title="延长共享有效期"
      >
        <div className="extend-form">
          <p>文档: {selectedShare?.document_title}</p>
          <p>当前过期时间: {selectedShare && formatDate(selectedShare.expires_at)}</p>
          
          <div className="form-group">
            <label htmlFor="extendDays">延长天数</label>
            <div className="days-selector">
              {[1, 3, 7, 14, 30].map(days => (
                <button 
                  key={days} 
                  className={`day-option ${extendDays === days ? 'selected' : ''}`}
                  onClick={() => setExtendDays(days)}
                >
                  {days}天
                </button>
              ))}
            </div>
          </div>
          
          <div className="modal-actions">
            <button 
              className="btn btn-secondary" 
              onClick={() => setShowExtendModal(false)}
            >
              取消
            </button>
            <button 
              className="btn btn-primary" 
              onClick={handleExtend}
            >
              确认延长
            </button>
          </div>
        </div>
      </Modal>
    </div>
  );
}

export default Shared; 